#include <cstring>

#include "./HttpResponse.h"
#include "../../tcp/code/utility/Buffer.h"

void HttpResponse::appendToBuffer(Buffer *buffer) const
{
    char buf[64]{};
    ::memset(buf, '\0', sizeof(buf));

    // 1.响应行
    // std::string要用c_str()适配snprintf()，否则乱码
    ::snprintf(buf, sizeof(buf), "HTTP/1.1 %d %s\r\n", this->statusCode_, this->statusMessage_.c_str());
    buffer->append(buf);

    // 2.响应头
    if (this->needCloseConnection_)
    {
        buffer->append("Connection: close\r\n");
    }
    else
    {
        buffer->append("Connection: Keep-Alive\r\n");
        ::snprintf(buf, sizeof(buf), "Content-Length: %zd\r\n", this->body_.size()); // z：无符号
        buffer->append(buf);
    }

    for (const auto &[key, value] : this->headers_)
    {
        ::snprintf(buf, sizeof(buf), "%s: %s\r\n", key.c_str(), value.c_str());
        buffer->append(buf);
    }
    buffer->append("\r\n");

    // 3.响应体
    buffer->append(this->body_);
}